<template>
  <div>
    <img src="../imgs/24_zhongqiu_mbanner_pc.png" height="80" width="100%"/>
    <el-header class="header">
      <div class="logo">
        <img src="../imgs/home_logoV1-2.png" height="60" width="474"/>
      </div>
      <el-menu :default-active="activeIndex" class="top-nav-menu" mode="horizontal" @select="handleSelect">
        <el-menu-item index="2" @click="shouye">首页</el-menu-item>
        <el-menu-item index="1" class="el-icon-headset">评论中心</el-menu-item>
        <el-menu-item index="3" class="login-menu-item">
          <el-dropdown v-if="username" @command="handleCommand">
            <span class="el-dropdown-link">
              你好, <span style="color: red">{{ username }}</span>
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <template v-else>
            你好，请登录注册
          </template>
        </el-menu-item>
        <el-menu-item>
          <el-avatar :size="60" :src="src" shape="square">
            <img src="../imgs/error.png" alt="头像"/>
          </el-avatar>
        </el-menu-item>
      </el-menu>
    </el-header>

    <!-- 评论列表 -->
    <el-button type="primary" @click="dialogFormVisible = true">添加评论</el-button>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="ping" ref="ping">
        <el-form-item label="评论语句" :label-width="formLabelWidth" prop="ping">
          <el-input v-model="ping.ping" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="引入评价照片" :label-width="formLabelWidth">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9091/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="ping.psrc" :src="ping.psrc" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary" @click="addPing">确 定</el-button>
      </div>
    </el-dialog>

    <!--展示所有评论-->
    <el-table
        ref="multipleTable"
        :data="pings"
        tooltip-effect="dark"
        style="width: 63%; position: relative; left: 50%; transform: translateX(-50%);"
    >
      <el-table-column label="" width="180">
        <template slot-scope="scope">
          <el-avatar :size="60" :src="scope.row.psrc" shape="square">
            <img src="../imgs/error.png" alt="默认头像"/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="ping" width="180"></el-table-column>
      <el-table-column prop="ptime" width="280"></el-table-column>
    </el-table>
  </div>
</template>

<script>
import {
  Header as ElHeader,
  Menu,
  MenuItem,
  Badge,
  Tooltip,
  Dropdown,
  DropdownMenu,
  DropdownItem,
  Input,
  Button,
  Select,
  Option,
  InputNumber,
  Aside,
  Main,
  Carousel,
  CarouselItem
} from 'element-ui';
import request from "@/utils/request";
import {removeToken} from "@/utils/auth";

export default {
  name: 'UserMain',
  components: {
    [ElHeader.name]: ElHeader,
    [Menu.name]: Menu,
    [MenuItem.name]: MenuItem,
    [Badge.name]: Badge,
    [Tooltip.name]: Tooltip,
    [Dropdown.name]: Dropdown,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Input.name]: Input,
    [Button.name]: Button,
    [Select.name]: Select,
    [Option.name]: Option,
    [InputNumber.name]: InputNumber,
    [Aside.name]: Aside,
    [Main.name]: Main,
    [Carousel.name]: Carousel,
    [CarouselItem.name]: CarouselItem,
  },
  data() {
    return {
      dialogFormVisible: false, // 控制对话框的显示和隐藏
      userForm: {
        id: 0,
        username: '',
        password: '',
        iphone: '',
        src: '',
      },
      activeIndex: '1', // 默认激活的菜单项
      cartCount: 0, // 购物车数量
      username: '', // 存储用户名
      src: '', // 存储头像地址
      user: { // 存储用户信息
        id: 0,
        username: '',
        src: ''
      },
      showCarousel: true, // 控制轮播图的显示
      showPersonalCenter: false, // 控制个人中心的显示
      title: '添加评论', // 模态框标题
      users: [], // 存储用户数据的数组
      dialogVisible: false, // 控制模态框显示
      formLabelWidth: '120px', // 表单项的标签宽度
      originalPassword: '', // 保存用于比较的原始密码
      uid: 0, // 用户id
      pings: [],
      ping: {
        id: 0,
        ping: '',
        psrc: '',
        ptime: '',
      }
    };
  },
  methods: {
    // addPing() {
    //   // 如果登入才能评论
    //   if (!this.user.username) {
    //     this.$message.error('请先登录');
    //     return;
    //   } else {
    //     if (!this.ping.ping || !this.ping.psrc) {
    //       this.$message.error('请填写完整的评论信息');
    //       return;
    //     }
    //     // 使用 Axios 发送 POST 请求到后端
    //     this.$axios({
    //       method: 'post',
    //       url: 'http://localhost:9091/ping/addPing', // 确保这个 URL 与后端接口匹配
    //       data: this.ping
    //     }).then(() => {
    //       this.$message.success('评论添加成功');
    //       // 重置表单
    //       this.$refs.ping.resetFields();
    //       this.ping.psrc = ''
    //       // 重新加载评论列表
    //       this.selectAllPing();
    //       // 关闭对话框
    //       this.dialogFormVisible = false;
    //     }).catch(error => {
    //       console.error('添加评论失败:', error);
    //       this.$message.error('评论添加失败');
    //     });
    //   }
    // },
    addPing() {
      // 检查用户是否已经登录
      if (!this.username) {
        this.$message.error('请先登录');
        return;
      }

      // 检查评论内容和头像是否已经填写
      if (!this.ping.ping || !this.ping.psrc) {
        this.$message.error('请填写完整的评论信息');
        return;
      }

      // 使用 Axios 发送 POST 请求到后端
      this.$axios({
        method: 'post',
        url: 'http://localhost:9091/ping/addPing', // 确保这个 URL 与后端接口匹配
        data: this.ping
      }).then(() => {
        this.$message.success('评论添加成功');
        // 重置表单
        this.$refs.ping.resetFields();
        this.ping.psrc = '';
        // 重新加载评论列表
        this.selectAllPing();
        // 关闭对话框
        this.dialogFormVisible = false;
      }).catch(error => {
        console.error('添加评论失败:', error);
        this.$message.error('评论添加失败');
      });
    },

    cancelSubmit() {
      this.dialogFormVisible = false; // 取消时关闭对话框
      this.$refs.ping.resetFields();
    },

    // 查看所有评论
    selectAllPing() {
      this.$axios({
        method: 'get',
        url: 'http://localhost:9091/ping/selectAllPing',
      }).then(res => {
        this.pings = res.data.data;
        console.log(this.pings)
      }).catch(err => {
        console.log(err);
      })
    },

    shouye() {
      this.$router.push('/');
    },
    handleAvatarSuccess(res) {
      // 假设后端返回的是上传文件的URL
      this.ping.psrc = res.data; // 确保这里是正确的属性
    },
    beforeAvatarUpload(file) {
      const isJPGorPNGorWebP = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPGorPNGorWebP) {
        this.$message.error('上传头像图片只能是 JPG, PNG 或 WebP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGorPNGorWebP && isLt2M;
    },

    handleSelect(key, keyPath) {
      if (key === '1') {
        this.showCarousel = true;
        this.showPersonalCenter = false;
      } else if (key === '3' && !this.username) {
        this.$router.push('/userLogin');
      } else {
        console.log('选中菜单项:', key, keyPath);
      }
    },

    // handleCommand(command) {
    //   if (command === 'logout') {
    //     this.username = '';
    //     this.src = '';
    //     removeToken();
    //     this.$router.replace('/').catch(err => {
    //       if (err.name !== 'NavigationDuplicated') {
    //         console.error(err);
    //       }
    //     });
    //   } else if (command === 'personal') {
    //     this.showPersonalCenter = true;
    //     this.showRecommendations = false;
    //     this.selectName();
    //   }
    // },
    handleCommand(command) {
      if (command === 'logout') {
        this.username = '';
        this.src = '';
        removeToken();
        this.$router.replace('/').catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            console.error(err);
          }
        });
        this.dialogFormVisible = false; // 关闭任何打开的对话框
      } else if (command === 'personal') {
        this.showPersonalCenter = true;
        this.showCarousel = false;
        this.selectName();
      }
    },

    getCookie(name) {
      let nameEQ = name + "=";
      let ca = document.cookie.split(';');
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
      }
      return '';
    },

    getToken() {
      request({
        method: 'post',
        url: 'http://localhost:9091/user/getTook',
      }).then(res => {
        if (res.data.code === 200) {
          console.log(res)
          if (res.data.data != null) {
            this.username = res.data.data.username
            this.users = res.data.data;
            this.users.username = this.username;
            this.src = res.data.data.src
            this.selectName();
            this.selectAllPing()
          }
        }
      })
    },

    //根据用户名查询
    selectName() {
      request({
        method: 'post',
        url: 'http://localhost:9091/user/selectOne',
      }).then(res => {
        if (res.data && res.data.data && res.data.data.src) {
          this.users = [res.data.data];// 将对象包装在数组中
          this.userForm = res.data.data;
          this.src = res.data.data.src;
          this.uid = res.data.data.id
          this.originalPassword = res.data.data.password; // 设置原始密码
          this.selectCreatCount();
        } else {
          console.error('头像数据获取失败');
        }
      })
    },

    selectCreatCount() {
      if (!this.username) {
        this.cartCount = 0;
      } else {
        this.$axios({
          method: 'post',
          url: 'http://localhost:9091/creat/selectCreatCount',
          params: {uid: this.uid},
        }).then(res => {
          if (res.data && res.data.data) {
            this.cartCount = res.data.data;
          } else {
            console.error('查询失败');
          }
        }).catch(error => {
          console.error('请求错误:', error);
        });
      }
    },
    errorHandler() {
      return true;
    },
  },
  created() {
    // this.username = this.getCookie('username');
    // this.user.username = this.username;
    // this.selectName();
    this.getToken()
  },
};
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  color: #333;
  height: 60px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
  margin-left: 24px;
}

.top-nav-menu {
  display: flex;
  justify-content: center;
  width: 70%;
  align-items: center;
}

.el-menu-item {
  padding: 0 20px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.el-menu-item:hover {
  background-color: #f5f5f5;
}

.el-menu-item.is-active {
  border-bottom: 2px solid #409EFF;
}

.el-avatar {
  border-radius: 50%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.footer {
  background-color: #a9c5a1;
  height: 275px;
  color: #fff;
  padding: 0 0;
  font-size: 14px;
  text-align: center;
  position: relative;
  top: -3px;
}

.container {
  width: 90%;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.footer-links, .footer-contact, .footer-legal, .footer-social {
  flex: 1;
  margin: 10px 0;
}

.footer-links h3, .footer-contact h3, .footer-legal, .footer-social {
  margin-bottom: 10px;
}

.footer-links ul {
  list-style: none;
  padding: 0;
}

.footer-links li {
  line-height: 1.5;
}

.footer-social .social-icon {
  display: inline-block;
  margin-right: 10px;
  font-size: 24px;
  transition: color 0.3s;
}

.footer-social .social-icon:hover {
  color: #ffd700;
}

@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }

  .footer-links, .footer-contact, .footer-legal, .footer-social {
    flex-basis: auto;
    width: 100%;
    margin-bottom: 20px;
  }
}

.personal-center {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.form-footer {
  margin-top: 20px;
  text-align: right;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>